      integer itmp(12),itmp0(12)
      real dif(12)
C**** replace GHCN (unit 2) by USHCN (unit 1) data; new file: unit 12
C**** assumption is that IDs are ordered numerically low->high in both
C****               input files

      open(3,file='ushcn-ghcn_offset_noFIL',form='formatted')
      open(1,file='USHCN.v2.mean_noFIL',form='formatted')
      open(2,file='v2.meany',form='formatted')
      open(12,file='v2.meanz',form='formatted')              ! output
!                                       CountryCode,ID,year,T-data
      read(3,*) iddiff,dif
   10 read(1,'(i3,i9,i4,12i5)',end=100) icc0,id0,iyr0,itmp0 ! read USHCN
       if(iddiff.lt.id0) read(3,*) iddiff,dif
   20 read(2,'(i3,i9,i4,12i5)',end=200) icc,id,iyr,itmp     ! read GHCN

      if(id.lt.id0.or.icc.ne.425) then
C****   just copy non-USHCN station (incl. non-US stations)
         write (12,'(i3,i9.9,i4,12i5)') icc,id,iyr,itmp !
         go to 20
      end if

!!!   if(id.gt.id0.or.iyr.gt.iyr0) stop 'should not happen'
      if(id.gt.id0.or.iyr.gt.iyr0) then
C**** id-GHCN>id-USHCN or same ID but extra years: merge in USHCN data
   30    write (12,'(i3,i9.9,i4,12i5)') icc0,id0,iyr0,itmp0
         write(*,'(a6,i9,i5,12i5)') 'ushcn ',id0,iyr0,itmp0
         read(1,'(i3,i9,i4,12i5)',end=100) icc0,id0,iyr0,itmp0 ! USHCN
         if(iddiff.lt.id0) read(3,*) iddiff,dif

         if(id.lt.id0) then                   ! until USHCN overtakes
           write (12,'(i3,i9.9,i4,12i5)') icc,id,iyr,itmp
           go to 20
         end if
         if(id.gt.id0.or.iyr.gt.iyr0) go to 30
      end if
                                              ! or catches up: id=id0
C***  skip early years not present in USHCN data
      if(iyr.lt.iyr0) then
!        write (12,'(i3,i9.9,i4,12i5)') icc,id,iyr,itmp
         write(*,'(a11,i9.9,i5,12i5)') 'skip v2.mn ',id ,iyr ,itmp
         go to 20
      end if
C***  replace GHCN by USHCN data if present
      if(iddiff.ne.id0) stop 'wrong iddiff'
      do m=1,12
      if(itmp0(m).gt.-9000) itmp0(m)=itmp0(m)-dif(m)
      end do
      write (12,'(i3,i9.9,i4,12i5)') icc0,id0,iyr0,itmp0
      go to 10

c**** No more USHCN data - copy data for remaining non-USHCN stations
  100 if(id.gt.id0.or.icc.ne.425)
     *        write(12,'(i3,i9.9,i4,12i5)') icc,id,iyr,itmp
  110 read(2,'(i3,i9,i4,12i5)',end=200) icc,id,iyr,itmp
      write(12,'(i3,i9.9,i4,12i5)') icc,id,iyr,itmp
      go to 110

  200 stop
      end
